package org.jeecg.modules.approve.refund.service.impl;

import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;

import org.jeecg.modules.approve.refund.entity.BikeApproveReturn;
import org.jeecg.modules.approve.refund.vo.BikeApproveReturnRes;
import org.jeecg.modules.approve.refund.mapper.BikeApproveReturnMapper;
import org.jeecg.modules.approve.refund.service.IBikeApproveReturnService;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.bicycle.order.vo.Refund;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.param.refund.entity.BikeMemberUserReturn;
import org.jeecg.modules.param.refund.mapper.BikeMemberUserReturnMapper;
import org.jeecg.modules.param.spend.entity.BikeMemberUserSpend;
import org.jeecg.modules.param.spend.mapper.BikeMemberUserSpendMapper;
import org.jeecg.modules.utils.AliPayKit;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 退款审批信息
 * @Author: 月月鸟
 * @Date: 2021-07-15
 * @Version: V1.0
 */
@Service
public class BikeApproveReturnServiceImpl extends ServiceImpl<BikeApproveReturnMapper, BikeApproveReturn> implements IBikeApproveReturnService {
    @Resource
    private BikeApproveReturnMapper bikeApproveReturnMapper;
    @Resource
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;
    @Resource
    private BikeMemberUserSpendMapper bikeMemberUserSpendMapper;
    @Resource
    private BikeMemberUserMapper bikeMemberUserMapper;
    @Resource
    private BikeMemberUserReturnMapper bikeMemberUserReturnMapper;

    @Override
    public Result<?> queryPageList(BikeApproveReturnRes bikeApproveReturn, Integer pageNo, Integer pageSize) {
        List<BikeApproveReturnRes> list = bikeApproveReturnMapper.queryPageList(bikeApproveReturn);
        for (BikeApproveReturnRes tb : list) {
            if (tb.getApproveStatus().equals("1")) {
                tb.setApproveYN("1");
            }
            if (tb.getApproveStatus().equals("2")) {
                tb.setApproveYN("0");
            }
        }
        return Result.OK(list);
    }

    @Override
    public Result<?> approve(BikeApproveReturn bikeApproveReturn) {

        //借车记录
        BikeVehicleOrder bikeVehicleOrderData = bikeVehicleOrderMapper.selectById(bikeApproveReturn.getOrderId());

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        bikeApproveReturn.setHandleBy(sysUser.getUsername());
        bikeApproveReturn.setHandleTime(new Date());
        if (bikeApproveReturn.getApproveYN().equals("1")) {
            //修改借车记录实际付款金额
            bikeVehicleOrderData.setPayActual(bikeVehicleOrderData.getPayActual().subtract(bikeApproveReturn.getFreeAmount()));
            //判断支付类型并退款
            //退款记录
            Refund refund = new Refund();
            refund.setId(bikeApproveReturn.getOrderId());
            refund.setRefundAmount(bikeApproveReturn.getFreeAmount());
            refund.setRefundReason(bikeApproveReturn.getApplyCause());
            Result<?> refund1 = this.refund(refund);
            //判断结果是否成功
            if (Objects.equals(refund1.getCode(), CommonConstant.SC_OK_200)) {
                bikeApproveReturn.setApproveStatus("1");
                bikeApproveReturnMapper.updateById(bikeApproveReturn);

                bikeVehicleOrderData.setBillStatus("4");
                bikeVehicleOrderMapper.updateById(bikeVehicleOrderData);
            }
            return refund1;
        } else {
            bikeVehicleOrderData.setBillStatus("4");
            bikeVehicleOrderMapper.updateById(bikeVehicleOrderData);
            bikeApproveReturn.setApproveStatus("2");
            bikeApproveReturnMapper.updateById(bikeApproveReturn);
            return Result.OK();
        }
    }

    private Result<?> refund(Refund refund) {
        Map<String, String> params = new HashMap<>();
        //查询消费记录 根据借车记录 id
        QueryWrapper<BikeMemberUserSpend> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", refund.getId());
        BikeMemberUserSpend bikeMemberUserSpend = bikeMemberUserSpendMapper.selectOne(wrapper);

        //退款记录
        BikeMemberUserReturn bikeMemberUserReturn = new BikeMemberUserReturn();

        //会员信息
        BikeMemberUser memberUserData = bikeMemberUserMapper.selectById(bikeMemberUserSpend.getUserId());
        //支付宝退款编码
        String outRequestNo = UUID.randomUUID().toString();

        //钱包退款
        if (bikeMemberUserSpend.getSpendType().equals("1")) {
            int i = refund.getRefundAmount().compareTo(bikeMemberUserSpend.getSpendAmount());
            if (i == 1) {
                return Result.error("退款金额大于订单金额");
            }
            BikeMemberUser memberUser = new BikeMemberUser();
            //会员信息表 id
            memberUser.setId(memberUserData.getId());
            //会员信息表 余额
            memberUser.setBalance(memberUserData.getBalance().add(refund.getRefundAmount()));
            //修改余额
            bikeMemberUserMapper.updateById(memberUser);
            //退款记录
            //借车订单
            bikeMemberUserReturn.setOrderId(bikeMemberUserSpend.getOrderId());
            //用户
            bikeMemberUserReturn.setUserId(bikeMemberUserSpend.getUserId());
            //钱包退款金额
            bikeMemberUserReturn.setReturnAmount(refund.getRefundAmount());
            //退款后余额
            bikeMemberUserReturn.setBalanceEnd(memberUserData.getBalance().add(refund.getRefundAmount()));
            //退款类型 1 钱包 2 支付宝 3 组合
            bikeMemberUserReturn.setReturnType("1");
            //退款原因备注
            bikeMemberUserReturn.setMemo(refund.getRefundReason());
            bikeMemberUserReturnMapper.insert(bikeMemberUserReturn);
            return Result.OK("余额退款成功");
        }
        //支付宝支付退支付宝
        if (bikeMemberUserSpend.getSpendType().equals("2")) {
            int i = refund.getRefundAmount().compareTo(bikeMemberUserSpend.getAliAmount());
            if (i == 1) {
                return Result.error("退款金额大于订单金额");
            }
            //商户订单号
            params.put("outTradeNo", bikeMemberUserSpend.getOutTradeNo());
            //退款金额
            params.put("refundAmount", refund.getRefundAmount().toString());
            //退款原因
            params.put("refundReason", refund.getRefundReason());
            //退款请求有号
            params.put("outRequestNo", outRequestNo);
            AlipayTradeRefundResponse ali = AliPayKit.refund(params);
            //如果状态码为 10000 则为退款成功
            if (ali.getCode().equals("10000")) {
                //退款记录
                //借车订单
                bikeMemberUserReturn.setOrderId(bikeMemberUserSpend.getOrderId());
                //用户
                bikeMemberUserReturn.setUserId(bikeMemberUserSpend.getUserId());
                //退款后余额
                bikeMemberUserReturn.setBalanceEnd(memberUserData.getBalance());
                //支付宝退款金额
                bikeMemberUserReturn.setAliAmount(refund.getRefundAmount());
                //退款类型 1 钱包 2 支付宝 3 组合
                bikeMemberUserReturn.setReturnType("2");
                //映射支付宝用户
                bikeMemberUserReturn.setAliUserId(bikeMemberUserSpend.getAliUserId());
                //映射支付宝订单编号
                bikeMemberUserReturn.setAliOrderId(bikeMemberUserSpend.getAliOrderId());
                //支付宝退款编号
                bikeMemberUserReturn.setAliRefundId(outRequestNo);
                //退款原因备注
                bikeMemberUserReturn.setMemo(refund.getRefundReason());
                bikeMemberUserReturnMapper.insert(bikeMemberUserReturn);
                return Result.OK("支付宝退款成功");
            } else {
                return Result.error(Integer.parseInt(ali.getCode()), ali.getMsg());
            }
        }
        //组合支付,各自原路退   优先支付宝
        if (bikeMemberUserSpend.getSpendType().equals("3")) {
            int i = refund.getRefundAmount().compareTo(bikeMemberUserSpend.getAliAmount().add(bikeMemberUserSpend.getSpendAmount()));
            if (i == 1) {
                return Result.error("退款金额大于金额");
            }
            int i1 = refund.getRefundAmount().compareTo(bikeMemberUserSpend.getAliAmount());
            //判断退款金额不大于 订单支付宝付款金额
            BikeMemberUser memberUser = new BikeMemberUser();
            //余额退款
            String returnAmount = "0";
            //支付宝退款
            String aliReturn = "0";
            if (i1 != 1) {
                //全部通过支付宝退款
                //商户订单号
                params.put("outTradeNo", bikeMemberUserSpend.getOutTradeNo());
                //退款金额
                aliReturn = refund.getRefundAmount().toString();
                params.put("refundAmount", aliReturn);
                //退款原因
                params.put("refundReason", refund.getRefundReason());
                //退款请求有号
                params.put("outRequestNo", outRequestNo);
            } else {
                //支付宝部分退款
                //商户订单号
                params.put("outTradeNo", bikeMemberUserSpend.getOutTradeNo());
                //支付宝支付金额全部退款
                aliReturn = bikeMemberUserSpend.getAliAmount().toString();
                params.put("refundAmount", aliReturn);
                //退款原因
                params.put("refundReason", refund.getRefundReason());
                //退款请求有号
                params.put("outRequestNo", outRequestNo);
                //多余部分余额退款   退款金额 - 支付宝退款金额  = 余额退款金额
                returnAmount = refund.getRefundAmount().subtract(bikeMemberUserSpend.getAliAmount()).toString();
                //会员信息表 id
                memberUser.setId(memberUserData.getId());
                //会员信息表 余额
                memberUser.setBalance(memberUserData.getBalance().add(new BigDecimal(returnAmount)));
            }
            //支付宝退款接口
            AlipayTradeRefundResponse ali = AliPayKit.refund(params);
            //退款记录
            //如果状态码为 10000 则为退款成功
            if (ali.getCode().equals("10000")) {
                //支付宝退款成功后，退余额
                //修改余额
                bikeMemberUserMapper.updateById(memberUser);
                //退款记录
                //借车订单
                bikeMemberUserReturn.setOrderId(bikeMemberUserSpend.getOrderId());
                //用户
                bikeMemberUserReturn.setUserId(bikeMemberUserSpend.getUserId());
                //支付宝退款金额
                bikeMemberUserReturn.setAliAmount(new BigDecimal(aliReturn));
                //余额退款金额
                bikeMemberUserReturn.setReturnAmount(new BigDecimal(returnAmount));
                //退款后余额
                bikeMemberUserReturn.setBalanceEnd(memberUser.getBalance());
                //退款类型 1 钱包 2 支付宝 3 组合
                bikeMemberUserReturn.setReturnType("3");
                //映射支付宝用户
                bikeMemberUserReturn.setAliUserId(bikeMemberUserSpend.getAliUserId());
                //映射支付宝订单编号
                bikeMemberUserReturn.setAliOrderId(bikeMemberUserSpend.getAliOrderId());
                //支付宝退款编号
                bikeMemberUserReturn.setAliRefundId(outRequestNo);
                //退款原因备注
                bikeMemberUserReturn.setMemo(refund.getRefundReason());
                bikeMemberUserReturnMapper.insert(bikeMemberUserReturn);
                return Result.OK("组合退款成功");
            } else {
                return Result.error(Integer.parseInt(ali.getCode()), ali.getMsg());
            }
        }
        return Result.OK("免单无需退款");
    }
}
